#!/bin/bash
[ $# -eq 0 ] && { echo "Usage: $0 <file1> [file2] ..."; exit 1; }

declare -A TOOL_MAP_SOURCES=(
    ['g\+\+']="\$CXX"
    ["gcc"]="\$CC"
    ["strip"]="\$STRIP"
    ["objcopy"]="\$OBJCOPY"
    ["readelf"]="\$READELF"
    ["nm"]="\$NM"
    ["ld"]="\$LD"
    ["ar"]="\$AR"
    ["as"]="\$AS"
)

declare -A TOOL_MAP_SPEC=(
    ['g\+\+']="%{__cxx}"
    ["gcc"]="%{__cc}"
    ["strip"]="%{__strip}"
    ["objcopy"]="%{__objcopy}"
    ["readelf"]="%{__readelf}"
    ["nm"]="%{__nm}"
    ["ld"]="%{__ld}"
    ["ar"]="%{__ar}"
    ["as"]="%{__as}"
)

process_file() {
    declare -n toolmap=$1
    local tmpfile=$2
    for cmd in ${!toolmap[@]} ;do
        replacement=$(sed 's/[\/&]/\\&/g' <<< "${toolmap[$cmd]}")
        sed -i -E "s/(^|\\s;|&|\\||<|>)(\\s*)${cmd}(\\s|$)/\\1\\2${replacement}\\3/g" $tmpfile
    done
}

for file in "$@"; do
    if [ ! -f $file ]; then
        continue
    fi
    tmpfile=$(mktemp "/tmp/check_XXXXXX.tmp")
    cp $file $tmpfile
    case $file in
        *.spec)
            process_file TOOL_MAP_SPEC $tmpfile
            ;;
        *.sh)
            process_file TOOL_MAP_SOURCES $tmpfile
            ;;
        *)
           continue
           ;;
    esac
    diff -u $file $tmpfile
    rm -f $tmpfile
done
